package com.yong.common.string;

public class SplitChinese {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("&&&&&&&&&&&&&&&&&&&&&&&");
		subCnString("我ABC", 4);
		subCnString("我ABC汉DEF", 6);
		subCnString("我ABC汉DEF", 7);
	}
	
	/**
	 * 定义中文字符Unicode编码范围
	 */
	private static final String CN_PATTERN = "[\\u4e00-\\u9fbb]+";
	
	public static final String subCnString(String str, int targetLen) {
		if (str == null || str.equals(""))
			return str;

		if (targetLen < 1)
			return "";

		if (str.length() <= targetLen) {
			return str;
		}

		int defaultLen = 0;

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			String s = str.substring(i, i + 1);

			int charLen = 1;
			if (s.matches(CN_PATTERN)) {
				charLen = 2;
			}

			if ((defaultLen + charLen) > targetLen) {
				break;
			}

			defaultLen += charLen;

			sb.append(s);
		}

		return sb.toString();
	}

}
